package com.nineclock.attendance.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
public class FeignInterceptor implements RequestInterceptor {
    /**
     * template  就是远程调用时 使用的请求对象
     * @param template
     */
    @Override
    public void apply(RequestTemplate template) {

        //从pc或者app的请求中获取认证信息,请求从哪来?
        //冲上下文中获取请求对象
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)requestAttributes;
            //之后可用这种方式获取请求或者响应对象
            HttpServletRequest request = servletRequestAttributes.getRequest();

            //从请求中获取认证信息
            String authorization = request.getHeader("Authorization");
            template.header("Authorization",authorization);

        }
    }
}
